package com.wonder.app.service;

import com.alibaba.druid.wall.WallSQLException;
import com.wonder.app.domain.PurInspectDetail;
import com.wonder.common.utils.StringUtils;

import com.wonder.constant.BillEvent;
import com.wonder.constant.BillType;
import com.wonder.utils.YzjUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class YzjService {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String WX_TOKEN = "YC88888888yc";

    @Getter
    private static String AppId;
    @Value("${yzj.appId}")
    public void setAppId(String appId) {
        AppId = appId;
    }
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     *@Author: hdx
     *@CreateTime: 20:46 2020/2/14
     *@param:  shareUrl 分享的url
     *@Description:  获取AccessToken
     */
    public String initJSSDKConfig(String url) throws Exception {

        //先从缓存中获取
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String accessToken = String.valueOf(valueOperations.get("accessToken"));
        //如果缓存中没有的话再去url获取
        if(StringUtils.isEmpty(accessToken) || "null".equals(accessToken)){
            accessToken = YzjUtil.getJSSDKAccessToken();
        }
        //accessToken存到redis中
        valueOperations.set("accessToken",accessToken,7200, TimeUnit.SECONDS);
        return accessToken;
    }

    public boolean checkSignature(String signature, String timestamp, String nonce) {
        String checktext = null;
        if (null != signature) {
            //对ToKen,timestamp,nonce 按字典排序
            String[] paramArr = new String[]{WX_TOKEN,timestamp,nonce};
            Arrays.sort(paramArr);
            //将排序后的结果拼成一个字符串
            String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                //对接后的字符串进行sha1加密
                byte[] digest = md.digest(content.toString().getBytes());
                checktext = byteToStr(digest);
            } catch (NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        }
        //将加密后的字符串与signature进行对比
        return checktext !=null ? checktext.equals(signature.toUpperCase()) : false;

    }

    /**
     *  将字节转化为十六进制字符串
     * @param myByte 字节
     * @return 字符串
     */
    private static String byteToHexStr(byte myByte) {
        char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        char[] tampArr = new char[2];
        tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
        tampArr[1] = Digit[myByte & 0X0F];
        String str = new String(tampArr);
        return str;
    }

    /**
     * 将字节数组转化我16进制字符串
     * @param byteArrays 字符数组
     * @return 字符串
     */
    private static String byteToStr(byte[] byteArrays){
        char[] buf = new char[byteArrays.length * 2];
        int index = 0;
        for (byte b : byteArrays){
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }
        return new String(buf);
    }

    /**
     * 质检不通过发送一条待办通知(采购员)
     * @param detail
     * @throws Exception
     */
    public void sendMsgToPur(PurInspectDetail detail ) throws Exception {
        //获取accesstoken
        String accesstoken = initJSSDKConfig("");
        YzjUtil.sendMsgToPur(accesstoken,detail);
    }

    /**
     * 有新的单据生成通知仓管部
     * @param data
     * @throws Exception
     */
    public void sendMsgToWare(Map<String,Object> data , String billType) throws Exception {
        //获取accesstoken
        String accesstoken = initJSSDKConfig("");
        YzjUtil.sendMsgToWare(accesstoken,data,billType);
    }

    /**
     * 超重发送一条待办通知(采购员)
     * @param billNo
     * @throws Exception
     */
    public void sendMsgToPur(String billNo ) throws Exception {
        //获取accesstoken
        String accesstoken = initJSSDKConfig("");
        YzjUtil.sendMsgToPurAbnor(accesstoken,billNo);
    }

    /**
     * 给质检部发送通知
     * @param data
     * @param billType
     * @throws Exception
     */
    public void sendMsgToQuality(Map<String, Object> data, String billType) throws Exception {
        //获取accesstoken
        String accesstoken = initJSSDKConfig("");
        YzjUtil.sendMsgToQuality(accesstoken,data,billType);
    }
}
